import axios, { AxiosError, AxiosResponse } from 'axios'
import { getToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'

type IResult = { code?: number, message?: string }
import store from '@/store'
import { RESET_TOEKN } from '@/store/modules/methods-type'

const service = axios.create({
  baseURL: process.env['VUE_APP_BASE_API '],
  timeout: 100000
})

service.interceptors.request.use(config => {
  const token = getToken()
  if ( token ) {
    config.headers.Authorization = `Bearer ${ token }`
  }
  return config
}, error => {
  return Promise.reject(error)
})

service.interceptors.response.use((response) => {
  const { code, message } = (response as AxiosResponse<IResult>).data
  if ( code !== 0 ) {
    ElMessage.error(message)
    return Promise.reject(message)
  }
  return response.data
}, (error: AxiosError) => {
  const res = error!.response
  if ( res && res.status === 401 ) {
    store.dispatch(`user/${ RESET_TOEKN }`).then(() => {
      window.location.reload()
    })
  }
  ElMessage.error(error.message)
  return Promise.reject(error)
})

export default service
